from sqlalchemy import Column, Integer, String, Boolean, DateTime, func
from sqlalchemy.sql.schema import Index

from app.utils.databases import Base
from app.utils.security import get_hash_password, verify_password


class User(Base):
    __tablename__ = "users"
    __table_args__ = (
        Index("idx_user_status", "is_active", "is_superuser"),  # 复合索引
        {"comment": "系统用户表"},
    )

    id = Column(Integer, primary_key=True, index=True, comment="用户唯一ID")
    username = Column(
        String(50), unique=True, index=True, nullable=False, comment="用户名(唯一)"
    )
    email = Column(
        String(100), unique=True, index=True, nullable=False, comment="用户邮箱(唯一)"
    )
    hashed_password = Column(String(255), nullable=False, comment="密码哈希值(BCrypt)")
    is_active = Column(
        Boolean,
        default=True,
        server_default="1",  # 数据库层面默认值
        comment="是否激活",
    )
    is_superuser = Column(
        Boolean, default=False, server_default="0", comment="是否超级管理员"
    )
    created_at = Column(
        DateTime(timezone=True), server_default=func.now(), comment="创建时间"
    )
    updated_at = Column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        comment="最后更新时间",
    )

    def __repr__(self):
        return f"<User(id={self.id}, username={self.username})>"
